import { defineStore } from 'pinia'
import { cloneDeep, round } from 'lodash'
import { storage } from '@/utils/Storage.ts'
import { queryFileFft } from '@/api/charts'
import operation from '@/common/operation'
import usePlayControl from './playControl'

const STORAGE_KEY = 'chartsStorage'
const STORE_KEY = 'chartsStore'

const useChartsStore = defineStore(STORE_KEY, {
  state: () => ({
    mode: 'dark', // light dark
    isLoadedLast: false, // 是否加载了最后一帧
    start: 0, // 在循环中的位置
    sequential: {
      value: null,
      currentRequest: null,
      query: null
    },
    settings: {
      step: 512, // 一次前进多少
      IQNum: 32768, // IQ点数
      simpleRate: 50 * 1e6, // 采样率 默认50M
      swpTime: 50, // 扫描时间，单位 us
      playbackRate: 1000 // 定时执行时间 单位ms
    },
    global: {
      refLevel: -20,
      samplingRate: 50000000,
      swpTime: 50, // 扫描时间，单位 us
      bitRate: 500000000,
      centerFreqIn: 0, // 中心频率
      dataOrganization: '0',
      dataType: '0',
      debugMode: '12',
      scale: 10, // 刻度
      fftSize: 1024,
      fileName: '',
      fileType: '0',
      intermediateFrequencyBandwidth: 0, // 中频带宽
      radarcenterFreqIn: 0, // 雷达中心频率
      radarintermediateFrequency: 0
    },
    // 文件信息
    file: {
      bitRate: null,
      centerFreqIn: null, // 中心频率
      dataType: null,
      debugMode: null,
      fftSize: null,
      fileName: null,
      fileType: null,
      intermediateFrequencyBandwidth: null,
      samplingRate: null,
      uploadTime: null,
      startOffset: null,
      cutoffLength: null
    },
    // 雷达文件信息
    radarfile: {
      fileName: null,
      uploadTime: null,
      radarNumber: null,
      collectionTime: null,
      fileTypeRadar: null, // 中心频率
      collectionMethod: null,
      intermediateFrequency: null,
      centerfreqIn: null,
      samplerateIn: null,
      samplingBw: null,
      samplingNum: null,
      quantizationBits: null,
      channelsNum: null,
      pulseCount: null
    },
    // 零扫宽视图
    zeroSpanViews: [],
    // 数字调制分析视图
    dmViews: [],
    sperctumArr: [],
    //下变频
    downConversion: {
      doubleMapKey: null,
      ddcFlag: false
    },
    radarDownConversion: {
      doubleMapKey: null,
      ddcFlag: false
    },
    //滤波标识
    filting: {
      doubleMapKey: null,
      filterFlag: false
    },
    radarFilting: {
      doubleMapKey: null,
      filterFlag: false
    },
    // 静态表格配置
    static: {
      enabled: true,
      dmLimit: 1024 // 静态信号解调显示个数限制
    },
    //参数估计
    paramsEstimate: {}
  }),
  getters: {
    // 总周期
    totalCycle() {
      const { IQNum, simpleRate } = this.settings
      return round((1e6 * IQNum) / simpleRate, 2)
    },
    // 一帧的点数
    viewNum() {
      const { IQNum } = this.settings
      const { swpTime } = this.global
      return round(IQNum * (swpTime / this.totalCycle))
    }
  },
  actions: {
    setStart(num) {
      this.start = num
    },
    setConfig(key, val) {
      this.settings[key] = val
      if (key === 'playbackRate') {
        usePlayControl().setPlaybackRate(val)
      } else if (key === 'swpTime') {
        this.setGlobal(key, val)
      }
    },
    setGlobal(key, value) {
      if (this.global[key] !== value) {
        operation.updateOptions(key, value)
        this.global[key] = parseInt(value)
      }
    },
    // 执行定时执行
    actionInterval(start) {
      this.setStart(start)
    },
    setFileInfo(info, path = '0') {
      const { uploadTime } = info
      if (uploadTime) {
        const reg = /-([0-9]+)-([0-9]+)\s([0-9]+):([0-9]+):/
        const uploadtimeStr = uploadTime.replace(reg, (...args) => {
          return args[1] + args[2] + args[3] + args[4]
        })
        this.file = { ...this.file, ...info }
        this.file.uploadTime = uploadtimeStr
        this.file.path = path
        const globalkeys = [
          'centerfreqIn',
          'debugMode',
          'samplingRate',
          'bitRate',
          'intermediateFrequencyBandwidth'
        ]
        globalkeys.forEach(key => {
          this.setGlobal(key, this.file[key])
        })
      }
    },
    setRadarInfo(info, path = '1') {
      const { uploadTime } = info
      if (uploadTime) {
        const reg = /-([0-9]+)-([0-9]+)\s([0-9]+):([0-9]+):/
        const uploadtimeStr = uploadTime.replace(reg, (...args) => {
          return args[1] + args[2] + args[3] + args[4]
        })
        this.radarfile = { ...this.radarfile, ...info }
        this.radarfile.uploadTime = uploadtimeStr
        this.radarfile.path = path
        // const globalkeys = [
        //   'centerFreqIn', //中心频率
        //   'samplerateIn', //采样率
        //   'debugMode',
        //   'samplingRate', //samplerateIn 采样率
        //   'bitRate',
        //   'intermediateFrequency' //中频
        // ]
        // globalkeys.forEach(key => {
        //   this.setGlobal(key, this.file[key])
        // })
        this.global.radarcenterFreqIn = this.radarfile.centerfreqIn
        this.global.radarintermediateFrequency = this.radarfile.intermediateFrequency
      }
    },
    getFileInfo() {
      return this.file
    },
    getRadarInfo() {
      return this.radarfile
    },
    setParamsEstimate(params) {
      this.paramsEstimate = params
    },
    setDownConversion(data) {
      this.downConversion.doubleMapKey = data.doubleMapKey
      this.downConversion.ddcFlag = data.ddcFlag
      this.filting.filterFlag = data.filterFlag
    },
    setRadarDownConversion(data) {
      this.radarDownConversion.doubleMapKey = data.doubleMapKey
      this.radarDownConversion.ddcFlag = data.ddcFlag
      this.radarFilting.filterFlag = data.filterFlag
    },
    getDownConversion() {
      return this.downConversion
    },
    getRadarDownConversion() {
      return this.radarDownConversion
    },
    setFilting(data) {
      this.filting.doubleMapKey = data.doubleMapKey
      this.downConversion.ddcFlag = data.ddcFlag
      this.filting.filterFlag = data.filterFlag
    },
    setRadarFilting(data) {
      this.radarFilting.doubleMapKey = data.doubleMapKey
      this.radarDownConversion.ddcFlag = data.ddcFlag
      this.radarFilting.filterFlag = data.filterFlag
    },
    setSperctum(data) {
      this.sperctumArr = data
    },
    getSperctum() {
      return this.sperctumArr
    },
    changeSperctum() {
      this.sperctumArr = []
    },
    getFilting() {
      return this.filting
    },
    getRadarFilting() {
      return this.radarFilting
    },
    getParamsEstimate() {
      return this.paramsEstimate
    },
    writeStorage() {
      storage.set(STORAGE_KEY, this.$state, 5000)
    },
    readStorage() {
      const result = storage.get(STORAGE_KEY)
      if (!result) {
        return
      }
      if (!this.file.fileName) {
        this.setFileInfo(result.file)
      }
      if (!this.radarfile.fileName) {
        this.setRadarInfo(result.radarfile)
      }
    },
    compareQuery(current, last) {
      let flag = false
      const keys = Object.keys(current)
      if (!last) {
        return false
      }
      for (let key of keys) {
        if (current[key] !== last[key]) {
          flag = true
          break
        }
      }
      return flag
    },
    querySequence() {
      const currentFileInfo = this.getFileInfo()
      if (this.compareQuery(currentFileInfo, this.sequential.query)) {
        this.sequential = {}
      }
      const { value, currentRequest } = this.sequential
      if (!value) {
        if (!currentRequest) {
          this.sequential.query = cloneDeep(this.getFileInfo())
          this.sequential.currentRequest = queryFileFft(this.sequential.query).then(rsp => {
            this.sequential.value = rsp
            this.setConfig('IQNum', rsp.data.pIQ_In)
            return rsp
          })
        }
        return this.sequential.currentRequest
      }
      return Promise.resolve(value)
    }
  }
})

export default useChartsStore
